//
//  MainCollectionVIewCellOfInt.m
//  UI_Project_A
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 GH. All rights reserved.
//

#import "MainCollectionVIewCellOfInt.h"
#import "TableViewCellOfInternet.h"
#import "HandleData.h"
#import "ModelOfInternet.h"
#import "ContectViewcontroller.h"
#import "FlowNewModel.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <DKNightVersion.h>





@interface MainCollectionVIewCellOfInt ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic ,retain)UITableView *tableview;
@property (nonatomic ,retain)NSMutableArray *arrliudongImage;
@property (nonatomic ,retain)NSMutableArray *arrLabel;
@property (nonatomic ,retain)UIScrollView *scroll;
@property (nonatomic ,retain)NSTimer *timer;
@property (nonatomic ,retain)UIButton *buttonOfRefresh;
@property (nonatomic ,retain)NSMutableArray *arrNid;
@property (nonatomic ,retain)NSString *strNid;

@end

@implementation MainCollectionVIewCellOfInt


- (void)dealloc {

    [_strNid release];
    [_arrNid release];
    [_tableview release];
    [_arrayOfData release];
    [_arrliudongImage release];
    [_scroll release];
    [_timer release];
    [_arrLabel release];
    [_buttonOfRefresh release];
    [super dealloc];
    
}



- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        [self handleData];
          [self createTableviewWithFrame:self.bounds];
        [self dataWithFlowNew];
        [self handleRefresh];
        [self RefreshButton];
        [self createKVCvalue];
        
       
    }

    return self;
}


- (void)createKVCvalue {
    //在conection上添加观察着
    [self.tableview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:@"context"];
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    CGFloat y = [[change objectForKey:@"new"] CGPointValue].y;
    

    if (y > 800) {
        self.buttonOfRefresh.hidden = NO;
    }else {
    
        self.buttonOfRefresh.hidden = YES;
    }
    
}





- (void)RefreshButton {

    self.buttonOfRefresh = [UIButton buttonWithType:UIButtonTypeCustom];

    self.buttonOfRefresh.frame = CGRectMake(30, self.frame.size.height - 180, 50, 50);
    [self  addSubview:self.buttonOfRefresh];
    [self.buttonOfRefresh setImage:[UIImage imageNamed:@"xiangxia2"] forState:UIControlStateNormal];
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 3, 50, 50) cornerRadius:25];
    
    self.buttonOfRefresh.layer.shadowPath = backgroundPath.CGPath;
    self.buttonOfRefresh.layer.shadowOpacity = 0.7;
     self.buttonOfRefresh.layer.shadowRadius = 0;
    self.buttonOfRefresh.layer.shadowColor = [[UIColor colorWithRed:0.0694 green:0.3703 blue:0.9978 alpha:1.0]CGColor];


    [self.buttonOfRefresh addTarget:self action:@selector(RefreshAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)RefreshAction:(UIButton *)button {
    
    

    self.tableview.contentSize = CGSizeZero;
    


}








#pragma mark - 刷新
- (void)handleRefresh {


    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self handleData];
        [self.tableview.mj_header endRefreshing];
        [self.tableview reloadData];
    }];
    
    self.tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self handleData];
        [self.tableview.mj_footer endRefreshing];
        [self.tableview reloadData];
    }];
    
    
  
}






#pragma mark - 流动新闻
- (void)dataWithFlowNew {
    
    if (!self.arrliudongImage) {
    self.arrliudongImage = [NSMutableArray array];
    }
    
    
    self.arrLabel = [NSMutableArray array];
    
    [HandleData handleFloewNewWithString:@"http://api.baiyue.baidu.com/sn/api/medianewslist?type=image&subtype=1&ln=200&an=10&wf=1&pd=newsplus&platform=andriod&ver=1" Block:^(id result) {
        
        
        NSDictionary * dicData = [result objectForKey:@"data"];
        
        NSArray *arr =  [dicData objectForKey:@"news"];
        
        for (NSDictionary *dic in arr) {
            
            if (self.arrLabel.count < 4) {
                [self.arrLabel addObject:[dic objectForKey:@"title"]];
                
                NSArray *arrimageurls = [dic objectForKey:@"imageurls"];
                
                
                NSDictionary *dicUrl = arrimageurls[0];
                
                 FlowNewModel *model = [[FlowNewModel alloc] init];
                 model.url = [dicUrl objectForKey:@"url"];
                  if (self.arrliudongImage.count < 4) {
                      [self.arrliudongImage addObject:model];
                  }
          }
        }
        [self createScrollView];
    }];
    
 
    
    
    
}


#pragma mark - 轮播图
- (void)createScrollView {
    
    
    
    if (self.arrliudongImage.count != 0) {
        
        
        [self.arrliudongImage addObject:self.arrliudongImage.firstObject];
        
        [self.arrliudongImage insertObject:[self.arrliudongImage objectAtIndex:self.arrliudongImage.count - 2]  atIndex:0];
        
        
        [self.arrLabel addObject:self.arrLabel [0]];
        
        [self.arrLabel insertObject:[self.arrLabel objectAtIndex:self.arrLabel.count - 2] atIndex:0];
    }
    
    
//    
    UIView *viewScroll = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 200)];
    viewScroll.backgroundColor = [UIColor blackColor];
//    [self.tableview addSubview:viewScroll];
    self.tableview.tableHeaderView = viewScroll;
    
    
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 200)];
   
    [viewScroll addSubview:self.scroll];
    self.scroll.contentSize = CGSizeMake(self.frame.size.width *self.arrLabel.count, 0);
    self.scroll.backgroundColor = [UIColor lightGrayColor];
    self.scroll.pagingEnabled = YES;
    self.scroll.showsHorizontalScrollIndicator = NO;
    [self.scroll release];
    
    for (int i = 0; i < self.arrliudongImage.count; i++) {
        
        FlowNewModel *model = self.arrliudongImage[i];
        
        UIImageView *imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
        
        [self.scroll addSubview:imageview];
        [imageview release];
        imageview.frame = CGRectMake(self.frame.size.width *i, 0, self.frame.size.width, 200);
        
        NSString *url = [self Substring:model.url];
        
        
        [imageview sd_setImageWithURL:[NSURL URLWithString:url]];
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10 + self.frame.size.width * i, 150, self.frame.size.width - 100, 50)];
        [self.scroll addSubview:label];
        
        [label release];
        label.numberOfLines = 0;
        
            label.text = self.arrLabel[i];
        
    }
    
    
    self.scroll.contentOffset = CGPointMake(self.frame.size.width, 0);
    
    //代理
    self.scroll.delegate = self;
    
    
    
    
    self.timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timerChanger) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.timer = _timer;
    
    

}

#pragma mark - 定时器
- (void)timerChanger {
    
    
    if (self.scroll.contentOffset.x == self.frame.size.width * 4) {
        
      
        
        [UIView animateWithDuration:0.3 animations:^{
            
            int contentOfset = (int)self.scroll.contentOffset.x;
            self.scroll.contentOffset = CGPointMake(contentOfset + self.frame.size.width, 0);
        }];
        
    }else {
        
        if (self.scroll.contentOffset.x == 0) {
            self.scroll.contentOffset = CGPointMake(self.frame.size.width * 4, 0);
        }
        if (self.scroll.contentOffset.x == self.frame.size.width * 5) {
            self.scroll.contentOffset = CGPointMake(self.frame.size.width, 0);
        }
        
       
        
        [UIView animateWithDuration:0.3 animations:^{
            
            int contentOfset = (int)self.scroll.contentOffset.x;
            
            self.scroll.contentOffset = CGPointMake(contentOfset + self.frame.size.width, 0);
        }];
    }
    
    
}




#pragma mark - 图片Url截取
- (NSString *)Substring:(NSString *)urlString {
    
    
    NSString *sub = urlString;
    
    if ([sub isEqualToString:@""]) {
        return nil;
    }
    
    
    if ([sub hasSuffix:@"jpg"]) {
        return urlString;
    }
    else {
        
        NSRange range = [urlString rangeOfString:@"u="];
        
        NSString *sub1 = [urlString substringFromIndex:range.location+2];
        
        NSRange lastRange = [sub1 rangeOfString:@"&"];
        sub = [sub1 substringToIndex:lastRange.location];
        
    }
    
    return sub;
}
















#pragma mark - 数据
- (void)handleData {
    
    self.strNid = @"http://api.baiyue.baidu.com/sn/api/medianewsinfo?type=image&subtype=1&nids=";
    self.arrNid = [NSMutableArray array];
    

[HandleData handleBlockWithurl:@"http://api.baiyue.baidu.com/sn/api/recommendlist" HTTPBody:@"wf=1&mid=8380B3E8589320AFC23220AB9C42D418%7C589951020642768&token=H4sIAAAAAAAAACWXa5LkIAyDL5QfgI1tTkNBIPc%2Fwnzu2a191KQDtizJ6tp91BHee1Er0mr0eWpX%0AbWM%2FVZuEemklRu3NxLXMPmK5tfVUcxvKo%2BFSio4oKrP6ucXLeKoXD9eQod68V%2B%2FNp4m91sweDe0l%0A3Kw218Z%2FJaZt%2B4yrn9qjR7Em0luv1lt0mebnfY99eXCVqF4LhcuorVCUS611NH0ouDSL0VWk5R09%0AprdWe6GfGDqqVpUeQS8RalPWN67peMLG4MJhLS%2BvFFfncr2q4zy1jZ5ltix3lGpqPm%2Fzs3cXSqqD%0AaqJVFwkXry3meltdW9tjQhOcOEoLBQ61MdcqpvXYMzxqSM13pHdz77OJj7PlUm75AcC%2FoxjT6WO2%0AtbeBLHc2HaPTdCldzCOazjgF3BZPs1EzAKgafBK0pn2ftU%2Fqr5luAdbDOLaHlj7LKe9lDE%2BVBggA%0AzFRbTlxV5xk3bhfQV8nf5gANak2bx%2Bw3x1XKbzZUpV1LBYzSixVAfI%2FUXX4nezepvXbJLuHU%2FGp9%0AC9BBp9EoCxxz3qpAUSej5BpZD3eVX62DpqmKI6bF0XovXFPTBKNQzK%2F8IT4Be3j7%2FGHWveaPGQ08%0ANS1lfjCRExksEDIx7mu%2FbsccW84e26GhtqoOV1pvGn14mfxJMF96gfBg1JhKgV3oZAbkpoHkQ%2FPh%0ANNqYgpThA%2B5nNfGd%2FjDGnpQYiqCatRZjXo23l2VPU0UorpqFIbA2YsJ6f1WoiJ7AHE6U4q2PUeuM%0AteLU2h9YKQ41UtC0C01nYYJQs%2FMiZ4UJsJmUzs903irL%2FfuxV7oMASYgQigMd8obus%2Bwh1p6QMEB%0ACslHGWW%2BsOitsR7OYpAjeZZHAIjO9d333YKMNRp4VCQe%2FKYtGTM%2Bldt3lkRBmhRsyFNSPGVebr9D%0A49Ef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EwPco3%2F3ZRILILoE4%0APLcOU88ird03t64TtyxPxCFotbCMfI0D3RhsEcsIQtpJ90Ntc9MZIPqT6w3OQLQMS7g%2FsUZ4CnMg%0AjEVJU8Nf8FSUi0Km%2BwGRr6bBRJZbfikhY1Odbx3Hx7q%2F0TE79lVhXJ5%2BzXAYY9xXf3TCtfEJjoZs%0AkJGEsXv%2FbKScaYZwAfETqoxFSBbITdf3W58d8jIFYC7QodhEwQirJoolbQBRZswonlluDiRLpEpn%0Ag8ODpMTOsZQIOpys1oNF%2FvROjGh4Sy57z6IEZ%2FNDlIDkwWH5hwCA1cK3lsmy87PzAB4RNnlM3CDn%0A4Zqz7o3o%2B3q6%2Fij4U1BSkc01971eWGdPzTWGTWBhxMfcIGRdWmzXRwYUeJwL2bmYmMinMApnrpZe%0AkMsPrpIGMo11J1qqfvIqGaSmN%2FySAC1nUCwmhJA72pcOBGXkFwcIzJ3gBTdmfzOVNa7l86zRStJN%0AqJgA6wEL6vKmPnAAtJyIYu89wzvfJ77W9Wwinoz0fuIHx%2BYQUx7YU899RtoFDPytgDQNkzzni8W8%0AXJH6yK2d2TpyERPX8Mwt7e7WUwGaXxUI2IWiqQqXiXsP8eyXWRlsgovqMvtQ2BS9bIsMR5glFBcZ%0AWHFuUUhx%2BljtfBlo%2BeYk6SS5uHJT4m3m2%2FY%2FjLhhnjoan8kIiUI%2BuXp63PySI8l0paLMTpQ%2Bc1ww%0AR5OpudTZnsQgvg0xHpl8syKyyptYJAMzTKNX4MQ5pzVSmV7JYJUZjjWcAsl4gfTMOiUr7%2FLljM0E%0Ay9hAkUuRdL%2F0g5tWHkTskC33Dym3IW4C%2BqWL77Q%2Fb%2BEWQioOAAA%3D%0A&withtoppic=1&mb=MX5&ln=200&from=news_smart&sv=5.8.4.0&an=20&ts=0&cuid=8380B3E8589320AFC23220AB9C42D418%7C589951020642768&topic=%E4%BA%92%E8%81%94%E7%BD%91&type=info&manu=Meizu&ver=4&" addValue:@"application/x-www-form-urlencoded; charset=UTF-8" HTTPHeaderField:@"Content-Type" Block:^(id result) {
    
    if (!self.arrayOfData) {
        self.arrayOfData = [NSMutableArray array];
    }
    
    
    
    
    NSDictionary *dic = [result objectForKey:@"data"];
    
    NSArray *arrNew = [dic objectForKey:@"news"];
    
    
    for (NSDictionary *dicNid in arrNew) {
        NSString * str = [dicNid objectForKey:@"nid"];
        [self.arrNid addObject:str];
    }
    
    for (int i = 0; i < 10; i++) {
        
        self.strNid = [self.strNid stringByAppendingFormat:@"%@,",self.arrNid[i]];
    }
    
    
    self.strNid = [self.strNid stringByAppendingString:@"&pd=newsplus&platform=andriod&ver=1"];

    
    [HandleData handleFloewNewWithString:self.strNid Block:^(id result) {
        
        NSDictionary *dic1 = [result objectForKey:@"data"];
        
        NSArray *arrNew1 = [dic1 objectForKey:@"news"];
        

        
        
    for (NSDictionary *dicNew in arrNew1) {
        if ([dicNew objectForKey:@"title"]) {
            ModelOfInternet *model = [[ModelOfInternet alloc]init];
            model.nid = [dicNew objectForKey:@"nid"];
            model.title = [dicNew objectForKey:@"title"];
            model.content = [dicNew objectForKey:@"content"];
            model.ts = [dicNew objectForKey:@"ts"];
            
            [self.arrayOfData addObject:model];
            [self.tableview reloadData];
            [model release];
            
            //image传值
            
            NSArray *arrcontent = [dicNew objectForKey:@"content"];
            
            //image传值
//            NSLog(@"%@",arrcontent);
//            NSDictionary * dicimage = arrcontent[0];
            
            
            for (NSDictionary * dicimage in arrcontent) {
                
            
            if ([[dicimage objectForKey:@"type"] isEqualToString:@"image"]) {
                NSDictionary *dicData = [dicimage objectForKey:@"data"];
   
              NSDictionary *dicsmall = [dicData objectForKey:@"small"];
                model.url = [dicsmall objectForKey:@"url"];
               
            }
            }
            
//            for (NSDictionary *diciamge in arrimage) {
//                model.url = [diciamge objectForKey:@"url"];
//                
//            }
            
        }
    }
    
    [self.tableview.mj_header endRefreshing];
    [self.tableview reloadData];

    }];
    
}];
    
    

    
    
    
}






- (void)createTableviewWithFrame:(CGRect)frame {
    
    
self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];

    [self addSubview:self.tableview];
    
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableview.dataSource = self;
    self.tableview.delegate = self;

    [self.tableview registerClass:[TableViewCellOfInternet class] forCellReuseIdentifier:@"CellOfInternet"];
    [self.tableview release];
    
    //tableview delegate
    self.tableview.delegate = self;
    
    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return self.arrayOfData.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    TableViewCellOfInternet *cell = [tableView dequeueReusableCellWithIdentifier:@"CellOfInternet"];
  
    ModelOfInternet *model = [self.arrayOfData objectAtIndex:indexPath.row];
    
    [cell passModelOfData:model];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],[UIColor colorWithWhite:0.247 alpha:1.000]);
    

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {



    return 130;
}


#pragma mark - tableVIew点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
// ModelOfInternet *model = [self.arrayOfData objectAtIndex:indexPath.row];
//
//    
//    [self.delegate pushContectViewWith:model];
    ModelOfInternet *model = [self.arrayOfData objectAtIndex:indexPath.row];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"ineternet" object:nil userInfo:@{@"content":model}];
    

   


}




- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    
    
    return 60;
}








@end
